package com.iqilu.ksd.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.iqilu.ksd.R;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.utils.CacheUtils;
import com.iqilu.ksd.utils.ImageUtils;
import com.jaeger.library.StatusBarUtil;
import com.oginotihiro.cropview.CropView;

import java.io.File;

/**
 * Created by Coofee on 2016/11/11.
 */

public class CropActivity extends BaseActivity {

    private String picPath;
    private ImageView btLeft;
    private TextView tvTitle;
    private ImageView btRight;
    private CropView cropView;

    private boolean isAvatar = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crop);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        initView();
        Intent intent = getIntent();
        isAvatar = intent.getBooleanExtra("isAvatar",false);
        picPath = intent.getStringExtra("picPath");
        File file = new File(picPath);
        if(isAvatar){
            cropView.of(Uri.fromFile(file)).withAspect(1, 1).initialize(this);
        }else {
            cropView.of(Uri.fromFile(file)).withAspect(16, 9).initialize(this);
        }

    }

    private void initView(){
        btLeft = getView(R.id.bt_left);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        btRight = getView(R.id.bt_right);
        cropView = getView(R.id.crop_view);
        tvTitle.setText(getString(R.string.live_crop_title));
        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btRight.setVisibility(View.VISIBLE);
        btRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = System.currentTimeMillis() + ".jpg";
                picPath = CacheUtils.getCacheDir(CropActivity.this) + name;
                Bitmap croppedBitmap = cropView.getOutput();
                ImageUtils.save(croppedBitmap,picPath, Bitmap.CompressFormat.JPEG);
                Intent intent = new Intent();
                intent.putExtra("thumb",picPath);
                setResult(Activity.RESULT_OK,intent);
                finish();
            }
        });
    }
}
